<template>
  <div>
    <top-footer>
      <!-- <template #search>
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
          <px-form-item label="科室">
            <px-select v-model="queryParams.className" filterable @change="classNameChange">
              <px-option v-for="item in classNameList" :key="item.id" :label="item.itemName" :value="item.itemValue" />
            </px-select>
          </px-form-item>
          <px-form-item label="报表类型">
            <px-select v-model="queryParams.reportType" clearable filterable>
              <px-option v-for="(item, index) in reportTypeList" :key="index" :label="item" :value="item" />
            </px-select>
          </px-form-item>
          <px-form-item label="报表名称">
            <px-input v-model="queryParams.reportName" clearable />
          </px-form-item>
          <px-form-item class="option-item">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </px-form-item>
        </px-form>
      </template> -->
      <template #btn>
        <p v-show="templateList.length > 0">当前共{{ templateList.length }}个模板</p>
      </template>
      <template #table="{ height }">
        <div ref="tempalteContentRef" v-loading="loading" class="template-content" :style="{ height: height + 'px' }">
          <div v-if="templateList.length > 0" class="template-list">
            <div
              v-for="(item, index) in templateList"
              :key="index"
              class="temp-item"
              :class="{ isLast: (index + 1) % len == 0 }"
              @click="openDialog(item)"
            >
              <p class="name">{{ item.name }}</p>
            </div>
          </div>
          <px-empty v-if="templateList.length == 0" />
        </div>
      </template>
      <!-- <template #foot>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="queryTable"
      />
    </template> -->
    </top-footer>
    <px-dialog v-model="previewDialog" title="模板预览" width="900" @close="closeDialog">
      <iframe id="preivewFrame" :src="templateUrl" width="100%" height="500" frameborder="0" />
      <template #footer>
        <!-- <px-button type="primary" plain style="position: relative; float: left" @click="downloadTempalte">下载模板</px-button> -->
        <span class="dialog-footer">
          <px-button @click="closeDialog">取消</px-button>
          <px-button type="primary" @click="gotoTemplate"> 使用 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import { queryReportType, queryChildByTypeCodeAndItemValue } from "@/api/report";
import { onMounted, reactive, toRefs, ref, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import { useElementSize } from "@vueuse/core";
import TopFooter from "../components/TopFooter.vue";
import { useRouterStoreHook } from "@/store/modules/router";
import axios from "axios";

const routerStore = useRouterStoreHook();

defineOptions({
  name: "COMMON_TEMPLATE_DETAIL"
});
const tempalteContentRef = ref();
const { width: templateWidth } = useElementSize(tempalteContentRef);
const len = computed(() => parseInt((templateWidth.value + 24) / 274));

const router = useRouter();

const classNameList = ref([]);
const reportTypeList = ref([]);
const templateList = ref([]);
const loading = ref(false);
const templateUrl = ref(null);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  className: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
  reportType: "",
  reportName: ""
});
const { VITE_FANRUAN_BASE_URL } = import.meta.env;

const queryTable = async () => {
  let reportPath = `reportCenter/${queryParams.className.toLocaleLowerCase()}`;
  try {
    loading.value = true;
    axios({
      method: "get",
      url: `/fineReport/webroot/decision/view/report/getcpts?path=${encodeURIComponent(reportPath)}`,
      headers: {
        "Content-Type": "application/json",
        facCode: localStorage.getItem("facCode") || ""
      }
    }).then(res => {
      if (res.status == 200) {
        templateList.value = res.data.files.map(v => {
          return {
            name: v.filename.split(".")[0],
            ext: v.filename.split(".")[1],
            templateName: encodeURIComponent(encodeURIComponent(v.path + "/" + v.filename.split(".")[0])) + "." + v.filename.split(".")[1]
          };
        });
      } else {
        console.log("出错了");
      }
      loading.value = false;
    });
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 18;
  queryTable();
}
const previewDialog = ref(false);
const previewItem = ref();
const openDialog = item => {
  previewDialog.value = true;
  previewItem.value = item;
  templateUrl.value = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${item.templateName}&__pi__=false&isModuleShow=true&facCode=${localStorage.getItem("facCode") || ""}`;
};
const closeDialog = () => {
  previewDialog.value = false;
  templateUrl.value = null;
};
const getReportType = async () => {
  const res = await queryReportType({ className: queryParams.className }); //ELECTRICTITY
  reportTypeList.value = res;
};
const getClassNameList = async () => {
  const res = await queryChildByTypeCodeAndItemValue({ typeCode: "className" });
  classNameList.value = res;
};
const classNameChange = () => {
  getReportType();
};
const gotoTemplate = () => {
  // let url = `/fullScreen/report/detail?template=${previewItem.value.templateName}&op=write`
  const path = "/fullScreen/report/detail";
  const query = { template: previewItem.value.templateName, op: "write" };
  const params = { path, query };
  const { href } = router.resolve(params);
  //let url = `${previewItem.value.url}&op=write&single_code=`
  window.open(href, "_blank");
};

const downloadTempalte = () => {
  document.getElementById("preivewFrame").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
};

onMounted(() => {
  getClassNameList();
  queryTable();
  // window.addEventListener("message", event => {
  //   if (event.origin !== "http://localhost:8075") return;
  //   debugger
  // });
});
</script>
<style scoped lang="scss">
.template-content {
  width: 100%;
}

.template-list {
  display: flex;
  flex-wrap: wrap;

  .temp-item {
    position: relative;
    width: 250px;
    height: 160px;
    margin-right: 24px;
    margin-bottom: 24px;
    color: #fff;
    cursor: pointer;
    background: url("@/assets/images/report-tpl-bg1.png") no-repeat;
    background-size: contain;

    &.isLast {
      margin-right: 0;
    }

    .name {
      position: absolute;
      bottom: 40px;
      left: 5%;
      width: 90%;
      text-align: center;
    }
  }
}
</style>
